<template>
	<view class="code-container">
		<button @click="getCode">{{ getFlag?`还剩${countdown}秒`:`获取验证码` }}</button>
	</view>
</template>

<script setup>
	import {
		defineProps,
		defineEmits,
		ref,
		onBeforeUnmount
	} from 'vue';
	const props = defineProps({
		email: {
			type: String,
			default: ''
		}
	});
	const emits = defineEmits(['transmitcode']);

	// 是否获取验证码的标志位
	const getFlag = ref(false);
	// 定时器
	const timer = ref(null);
	// 倒计时，验证码有效期
	const countdown = ref(60);

	const getCode = () => {
		if (getFlag.value) return;
		// 判断邮箱是否为空
		if (!props.email) return;
		// 验证邮箱格式
		const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
		if (!reg.test(props.email)) {
			uni.showToast({
				title: '请输入正确的邮箱格式',
				icon: 'none'
			});
			return;
		};


		// 发送验证码
		uniCloud.callFunction({
			name: 'getCode',
			data: { mail: props.email },
			success: res => {
				uni.showToast({
					title: '验证码已发送',
					icon: 'success'
				});
				// 将获得的验证码交给父组件进行判断
				emits('transmitcode', res.result.data.code);
				getFlag.value = true;
				timer.value = setInterval(() => {
					countdown.value--;
					if (countdown.value <= 0) {
						clearInterval(timer.value);
						getFlag.value = false;
						countdown.value = 60;
						// 超过60秒，则此验证码将失效
						emits('transmitcode', '');
					}
				}, 1000);
			},
			fail: err => {
				uni.showToast({
					title: '验证码发送失败',
					icon: 'none'
				});
			}
		});


	};
	// 组件销毁时清除定时器
	onBeforeUnmount(() => {
		clearInterval(timer.value);
	});
</script>

<style scoped lang="scss">
	.code-container {
		width: 220rpx;
		height: 80rpx;

		button {
			width: 100%;
			height: 100%;
			font-size: 28rpx;
			line-height: 80rpx;
			color: pink;
			font-weight: bolder;
		}
	}
</style>